/**
 * 封装 axios 请求模块
 */
import axios from "axios"

import jsonBig from 'json-bigint'

// 导入 Vuex
import store from '../store'

const baseURL = 'http://ttapi.research.itcast.cn/app'

// axios.create 方法：复制一个 axios
const request = axios.create({
  baseURL // 基础路径
})

// 请求拦截器
request.interceptors.request.use(
  function (config) {
    // 如果 Vuex 中有令牌就设置到协议头上
    if (store.state.user) {
      config.headers.Authorization = 'Bearer ' + store.state.user.token
    }
    // Do something before request is sent
    return config
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response
  },
  function (error) {
    // 没有登录或者令牌过期了
    if (error.response.status == 401) {
      // 判断本地是否有令牌
      if (store.state.user) {
        // 使用 刷新令牌 重新更新令牌
        axios.put(baseURL + '/v1_0/authorizations', {}, {
          headers: {
            Authorization: 'Bearer ' + store.state.user.refresh_token
          }
        }).then(res => {
          // 更新本地令牌
          store.commit('setToken', res.data.data.token)
          // 重新调用接口
          // return request.get(error.config.url)

        })
      }
    }

    return Promise.reject(error);
  }
)

request.defaults.transformResponse = [function (data) {
  try {
    return jsonBig.parse(data)
  } catch (err) {
    return {}
  }
}]

export default request